using System;
using UnityEngine;

public class DemoJSCallback
{
    private string deviceInfo = "";
    private OpenHarmonyJSObject m_ohJSDeviceInfoObject = null;
    private OpenHarmonyJSObject m_ohJSSensorObject = null;
    private OpenHarmonyJSCallback m_callback = null;

    public delegate void OnSensorCallack(string msg);

    private OnSensorCallack mCallack = null;
    
    public string Test(OnSensorCallack callack)
    {
        deviceInfo = string.Empty;
        mCallack = callack;

        TestSystemModule();
        TestJSCallback();

        return string.Empty;
    }

    public void Stop()
    {
        mCallack = null;
    }

    void TestSystemModule()
    {
        m_ohJSDeviceInfoObject = new OpenHarmonyJSObject("DeviceInfo");

        var deviceType = m_ohJSDeviceInfoObject.Call<string>("getDeviceType");
        var majorVersion = m_ohJSDeviceInfoObject.Call<Int64>("getMajorVersion");
        var seniorVersion = m_ohJSDeviceInfoObject.Call<Int64>("getSeniorVersion");

        deviceInfo = $"deviceType={deviceType}\nmajorVersion={majorVersion}\nseniorVersion={seniorVersion}"; 
        Debug.Log(deviceInfo);
    }

    void TestJSCallback()
    {
        m_ohJSSensorObject = new OpenHarmonyJSObject("Sensor");
        m_callback = new OpenHarmonyJSCallback(CallbackFromTS);
        // 参数: https://docs.openharmony.cn/pages/v4.0/en/application-dev/reference/apis/js-apis-sensor.md#sensorid9
        m_ohJSSensorObject.Call("on", 1, m_callback);
    }

    object CallbackFromTS(params OpenHarmonyJSObject[] args)
    {
        // 这里需要注意的是返回值类型是 OpenHarmonyJSObject
        OpenHarmonyJSObject data = args[0];
        var x = data.Get<float>("x");
        var y = data.Get<float>("y");
        var z = data.Get<float>("z");
        var biasX = data.Get<float>("biasX");
        var biasY = data.Get<float>("biasY");
        var biasZ = data.Get<float>("biasZ");

        var sensorData = $"Sensor: xyz=({x}, {y}, {z}) bias=({biasX}, {biasY}, {biasZ})";
        Debug.Log(sensorData);
        if (mCallack != null)
            mCallack($"deviceInfo={deviceInfo}\n\nSensor={sensorData}");
        return null;
    }
}
